/*
 * Created on 05.08.2003
 * 
 * AiDA 2.2 Format Publisher Local Projects Database (c) 2003 eRomania Gateway
 */
package ro.gateway.aida.servlet;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import org.idmlinitiative.resources.dtds.aida22.Activities;
import org.idmlinitiative.resources.dtds.aida22.ActivityType;
import org.idmlinitiative.resources.dtds.aida22.DateType;
import org.idmlinitiative.resources.dtds.aida22.DocLinkType;
import org.idmlinitiative.resources.dtds.aida22.FreeTextType;
import org.idmlinitiative.resources.dtds.aida22.FundingType;
import org.idmlinitiative.resources.dtds.aida22.HyperTextType;
import org.idmlinitiative.resources.dtds.aida22.IDType;
import org.idmlinitiative.resources.dtds.aida22.LocationType;
import org.idmlinitiative.resources.dtds.aida22.MoneyType;
import org.idmlinitiative.resources.dtds.aida22.ObjectFactory;
import org.idmlinitiative.resources.dtds.aida22.OrgRole;
import org.idmlinitiative.resources.dtds.aida22.OrgRoleType;
import org.idmlinitiative.resources.dtds.aida22.OrgType;
import org.idmlinitiative.resources.dtds.aida22.PersonRole;
import org.idmlinitiative.resources.dtds.aida22.PersonRoleType;
import org.idmlinitiative.resources.dtds.aida22.PersonType;
import org.idmlinitiative.resources.dtds.aida22.RelatedType;
import org.idmlinitiative.resources.dtds.aida22.SectorType;
import org.idmlinitiative.resources.dtds.aida22.SpiderType;
import org.idmlinitiative.resources.dtds.aida22.StatusType;
import org.idmlinitiative.resources.dtds.aida22.YearlyType;

import ro.gateway.aida.admin.PropertyListItem;
import ro.gateway.aida.db.DBPersistenceManager;
import ro.gateway.aida.db.PersistenceManager;
import ro.gateway.aida.db.PersistenceToken;
import ro.gateway.aida.fnd.FundingByCatItem;
import ro.gateway.aida.fnd.FundingItem;
import ro.gateway.aida.fnd.FundingYearlyItem;
import ro.gateway.aida.obj.AIDALocation;
import ro.gateway.aida.obj.AIDAObjSector;
import ro.gateway.aida.obj.AIDASector;
import ro.gateway.aida.obj.Activity;
import ro.gateway.aida.obj.ActivityRelation;
import ro.gateway.aida.obj.ActivityStatus;
import ro.gateway.aida.obj.AidaResource;
import ro.gateway.aida.obj.GenericActivityProperty;
import ro.gateway.aida.obj.Organization;
import ro.gateway.aida.obj.OrganizationInv;
import ro.gateway.aida.obj.OrganizationRole;
import ro.gateway.aida.obj.PersonInv;
import ro.gateway.aida.obj.db.ActivityDB;
import ro.gateway.aida.utils.HttpUtils;
import ro.gateway.aida.utils.PublisherDateFormatter;
import ro.gateway.aida.utils.SysProp;
import ro.gateway.aida.utils.Utils;
import ro.xblue.translator.Translator_DB;
/**
 * @author Mihai Postelnicu
 * 
 * e-mail (mihai@ro-gateway.org) (c) 2003 by eRomania Gateway
 */
public class PublisherServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ServletContext application = this.getServletContext();
		StringBuffer ctxb = request.getRequestURL();
		ctxb.delete(ctxb.length() - 14, ctxb.length());
		String ctx = ctxb.toString();
		response.setContentType("text/xml");
		//parameters
		Enumeration epn=request.getParameterNames();
		String maxblocksize="MaxBlockSize";
		String startwith="StartWith";
		while (epn.hasMoreElements()) {
			String param = (String) epn.nextElement();
			if(param.toLowerCase().equals("maxblocksize")) maxblocksize=param;
			if(param.toLowerCase().equals("startwith")) startwith=param;
		}
		
		
		long maxBlockSize = HttpUtils.getLong(request, maxblocksize, 0);
		long startWith = HttpUtils.getLong(request, startwith, 0);
		String count = HttpUtils
				.getValidTrimedString(request, "count", "false");
		PersistenceToken token = PersistenceManager.tokenLookup(application);
		DBPersistenceManager db = new DBPersistenceManager(token);
		Connection con = db.getConnection();
		long nextFirstPrjID = 0;
		try {
			ObjectFactory objFactory = new ObjectFactory();
			Activities acts = objFactory.createActivities();
			//initialize AiDA XML Stylesheet Objects package
			JAXBContext jc = JAXBContext
					.newInstance("org.idmlinitiative.resources.dtds.aida22");
			StringBuffer countOUT = new StringBuffer(); //the SMALL XML for
			// counting projects
			countOUT.append("<?xml version='1.0' encoding='windows-1252' ?>");
			countOUT.append("<activityCount>");
			try {
				String sql = "select id from activities where id>=? order by id";
				String countSql = "select count(*) from activities";
				if ("true".equals(count)) {
					PreparedStatement ps = con.prepareStatement(countSql);
					ResultSet rs = ps.executeQuery();
					if (rs.next()) {
						countOUT.append(rs.getLong(1));
						countOUT.append("</activityCount>");
					}
				} else {
					//this query should be optimized to extract more
					// efficiently
					PreparedStatement ps = con.prepareStatement(sql);
					ps.setLong(1, startWith);
					ResultSet rs = ps.executeQuery();
					long prjcount = 0;
					while (rs.next()) {
						if ((maxBlockSize != 0) && (++prjcount > maxBlockSize)) {
							nextFirstPrjID = rs.getLong(1);
							break;
						}
						//retrieve project data
						Activity ain = ActivityDB.getManager(token)
								.getAllDataById(rs.getInt(1));
						if (ain.getObject() == null) {
							continue;
						}
						ActivityType aout = objFactory.createActivityType();
						//binding IDs
						//ain=activity in ; aout=activity out->the beans that
						// will be marshalled
						OrganizationInv[] donor_orgs = ain
								.getOrgsByLRId(OrganizationRole.DONOR_ORG_ROLE);
						List aout_id = aout.getID();
						if (donor_orgs != null) {
							for (int i = 0; i < donor_orgs.length; i++) {
								String donor_id = ain
										.getDonorIdForOrg(donor_orgs[i]
												.getOrg().getId());
								if (donor_id == null) {
									continue;
								}
								IDType id = objFactory.createIDType();
								OrgType org_assigned = objFactory
										.createOrgType();
								try {
									org_assigned.setRefKey(donor_orgs[i]
											.getOrg().getAIDAOrg());
								} catch (NumberFormatException e) {
									e.printStackTrace();
								}
								org_assigned.setLang(Constants.DEFAULT_LANGUAGE);
							
								org_assigned.setValue(donor_orgs[i].getOrg()
										.getName().getString(Constants.DEFAULT_LANGUAGE));
								id.setAssigningOrg(org_assigned);
								id.setUniqID(donor_id);
								aout_id.add(id);
							}
						}
						//binding title
						GenericActivityProperty gen_titles = ain
								.getGen_titles();
						String[] gen_titles_langs = gen_titles
								.getAvailableLanguages();
						List aout_title = aout.getTitle();
						if (gen_titles_langs != null) {
							for (int i = 0; i < gen_titles_langs.length; i++) {
								FreeTextType title = objFactory
										.createFreeTextType();
								title.setLang(gen_titles_langs[i]);
								title.setValue(gen_titles
										.getName(gen_titles_langs[i]));
								aout_title.add(title);
							}
						}
						//binding locations
						AIDALocation[] ain_loc = ain.getLocations();
						List aout_loc = aout.getLocation();
						if (ain_loc != null) {
							for (int i = 0; i < ain_loc.length; i++) {
								LocationType location = objFactory
										.createLocationType();
								if (ain_loc[i].getCountry() != null) {
									location.setLocationCode(ain_loc[i]
											.getCountry().getIso3());
									location.setValue(ain_loc[i].getCountry()
											.getName());
									location.setLang(Constants.DEFAULT_LANGUAGE);
									aout_loc.add(location);
								}
								//TODO: cregion...
								//else
								// location.setLocationCode(ain_loc[i].getCregion().get)
							}
						}
						//binding dates
						DateType aout_date_start = objFactory.createDateType();
						DateType aout_date_end = objFactory.createDateType();
						Calendar cals = Calendar.getInstance();
						Calendar cale = Calendar.getInstance();
						cals.setTimeInMillis(ain.getDate_as());
						cale.setTimeInMillis(ain.getDate_ae());
						//aout_date_start.setAttributeAddedBy("RoDG");
						aout_date_start.setDate(cals.getTime());
						aout_date_start.setValue(PublisherDateFormatter.valuePrint(cals.getTime()));
						aout_date_end.setDate(cale.getTime());
						aout_date_end.setValue(PublisherDateFormatter.valuePrint(cale.getTime()));
						//aout_date_end.setAttributeAddedBy("RoDG");
						aout.setStartDate(aout_date_start);
						aout.setEndDate(aout_date_end);
						//binding status code
						ActivityStatus ain_stat = ain.getStatus();
						if (ain_stat != null) {
							String[] ain_stat_langs = ain_stat
									.getAvailableLangs();
							StatusType status = objFactory.createStatusType();
							if (ain_stat_langs != null) {
								for (int i = 0; i < ain_stat_langs.length; i++) {
									status.setStatusCode((short) ain_stat
											.getSt_code());
									status.setValue(ain_stat.getStatus(Constants.DEFAULT_LANGUAGE));
									status.setLang(Constants.DEFAULT_LANGUAGE);
									aout.setStatus(status);
									//TODO: just one status lang!
									break;
								}
							}
						}
						//binding sectors code
						AIDAObjSector[] ain_sectors = ain.getSectors();
						List aout_sectors = aout.getSector();
						if (ain_sectors != null) {
							for (int i = 0; i < ain_sectors.length; i++) {
								SectorType sector = objFactory
										.createSectorType();
								AIDASector t = ain_sectors[i].getSector();
								sector.setValue(t.getTitle(Constants.DEFAULT_LANGUAGE));
                                int refkey=0;
                               try {

                                    refkey = Integer.parseInt(t.getCrs_code());
                                    
                                } catch (NumberFormatException e) {

                                }
                                
                                
								sector.setRefKey(refkey);
								sector.setLang(Constants.DEFAULT_LANGUAGE);
								aout_sectors.add(sector);
							}
						}
						//binding notes
						GenericActivityProperty ain_obj = ain
								.getGen_objectives();
						List aout_notes = aout.getNotes();
						//GenericActivityProperty
						// ain_res=ain.getGen_results();
						//TODO: only objectives are treated as notes for the
						// moment
						String[] ain_obj_langs = ain_obj
								.getAvailableLanguages();
						if (ain_obj_langs != null) {
							for (int i = 0; i < ain_obj_langs.length; i++) {
								FreeTextType notes = objFactory
										.createFreeTextType();
								notes.setLang(ain_obj_langs[i]);
								notes.setValue(ain_obj
										.getName(ain_obj_langs[i]));
								aout_notes.add(notes);
							}
						}
						//binding funding
						OrganizationInv[] funding_orgs = ain
								.getOrgsByLRId(OrganizationRole.FINANCING_ORG_ROLE);
						//binding crazy empty funding object! :(
						FundingItem[] ain_funding = ain.getFunding_itemsArray();
						boolean fobj = false;
						int ii;
						if (funding_orgs != null)
							for (ii = 0, fobj = false; ii < funding_orgs.length; ii++) {
								if (ain_funding != null)
									for (int j = 0; j < ain_funding.length; j++)
										if (ain_funding[j].getOrg().getId() == funding_orgs[ii]
												.getOrg().getId())
											fobj = true;
								if (!fobj) {
									FundingType aout_funding = objFactory
											.createFundingType();
									FundingType.FundingOrg fo = objFactory
											.createFundingTypeFundingOrg();
									fo.setValue(funding_orgs[ii].getOrg()
											.getName().getString(Constants.DEFAULT_LANGUAGE));
									fo.setRefKey(funding_orgs[ii].getOrg()
											.getAIDAOrg());
									fo.setLang(Constants.DEFAULT_LANGUAGE);
									List aout_flist = aout_funding.getContent();
									aout_flist.add(fo);
									aout.getFunding().add(aout_funding);
								}
							}
						if (ain_funding != null) {
							for (int i = 0; i < ain_funding.length; i++) {
								FundingItem item = ain_funding[i];
								FundingType aout_funding = objFactory
										.createFundingType();
								List aout_flist = aout_funding.getContent();
								//binding funding org
								FundingType.FundingOrg fo = objFactory
										.createFundingTypeFundingOrg();
								Organization bo = item.getOrg();
								fo.setValue(bo.getName().toString());
								fo.setRefKey(bo.getAIDAOrg());
								fo.setLang(Constants.DEFAULT_LANGUAGE);
								aout_flist.add(fo);
								//binding yearly items
								FundingYearlyItem[] ain_funding_yearly = item
										.getYearlyItemsArray();
								if (ain_funding_yearly != null) {
									for (int j = 0; j < ain_funding_yearly.length; j++) {
										FundingYearlyItem itemy = ain_funding_yearly[j];
										FundingType.Yearly fy = objFactory
												.createFundingTypeYearly();
										Calendar year = Calendar.getInstance();
										year.setTimeInMillis(itemy
												.getStart_date());
										DateType date = objFactory
												.createDateType();
										date.setDate(year.getTime());
										date
												.setValue(PublisherDateFormatter.valuePrint(year.getTime()));
										fy.setYearStarting(date);
										MoneyType mt = objFactory
												.createMoneyType();
										mt.setAmount(BigDecimal.valueOf(itemy
												.getAmount()));
										mt.setCurrency(itemy.getCurrency());
										mt.setValue(Long.toString(itemy
												.getAmount())+" "+itemy.getCurrency());
										fy.getAmount().add(mt);
										aout_flist.add(fy);
									}
								}
								//bind the total
								FundingType.Total ft = objFactory
										.createFundingTypeTotal();
								ft.setAmount(BigDecimal.valueOf((long) item
										.getAmount()));
								ft.setCurrency(item.getCurrency());
								ft.setValue(NumberFormat.getNumberInstance()
										.format(item.getAmount())+" "+item.getCurrency());
								if (ft.getAmount().longValue() != 0)
									aout_flist.add(ft);
								//bind byCategory items
								FundingByCatItem[] ain_funding_byCat = item
										.getByCatItemsArray();
								for (int j = 0; (ain_funding_byCat != null)
										&& (j < ain_funding_byCat.length); j++) {
									FundingByCatItem itemc = ain_funding_byCat[j];
									FundingType.ByCategory fCat = objFactory
											.createFundingTypeByCategory();
									FreeTextType name = objFactory
											.createFreeTextType();
									GenericActivityProperty comp = itemc
											.getComponent();
									name.setLang(Constants.DEFAULT_LANGUAGE);
									name.setValue(comp.getName(Constants.DEFAULT_LANGUAGE));
									fCat.setCategory(name);
									FundingYearlyItem[] cfy = itemc
											.getYearlyItemsArray();
									for (int k = 0; (cfy != null)
											&& (k < cfy.length); k++) {
										FundingYearlyItem y = cfy[k];
										YearlyType yt = objFactory
												.createYearlyType();
										MoneyType mt = objFactory
												.createMoneyType();
										mt.setAmount(BigDecimal.valueOf(y
												.getAmount()));
										mt.setCurrency(y.getCurrency());
										mt.setValue(Long
												.toString(y.getAmount())+" "+y.getCurrency());
										yt.getAmount().add(mt);
										Calendar year = Calendar.getInstance();
										year.setTimeInMillis(y.getStart_date());
										DateType date = objFactory
												.createDateType();
										date
												.setValue(PublisherDateFormatter.valuePrint(year.getTime()));
										date.setDate(year.getTime());
										yt.setYearStarting(date);
										fCat.getCatYearly().add(yt);
									}
									MoneyType mt = objFactory.createMoneyType();
									mt.setAmount(BigDecimal.valueOf(itemc
											.getAmount()));
									mt.setCurrency(itemc.getCurrency());
									mt.setValue(Long
											.toString(itemc.getAmount())+" "+itemc.getCurrency());
									fCat.getCatTotal().add(mt);
									aout_flist.add(fCat);
								}
								//end byCat
								//add terms assist
								FundingType.TermsAssist ta_out = objFactory
										.createFundingTypeTermsAssist();
								PropertyListItem ta_in = item
										.getTerms_of_assistance();
								if (ta_in != null) {
									ta_out.setValue(ta_in.getString(Constants.DEFAULT_LANGUAGE));
									ta_out.setLang(Constants.DEFAULT_LANGUAGE);
									ta_out.setTerms((short) ta_in.getId());
									aout_flist.add(ta_out);
								}
								//add the funding item to the project
								aout.getFunding().add(aout_funding);
							}
						}
						//end funding
						//bind dbKey:
						aout.setDbKey(Long.toString(ain.getId()));
						aout.setRights((short) 0);
						//bind origin - 100 for RoDG, this should be set
						//aout.setOrigin((short) 100);
						//bind modify date
						Calendar modif = Calendar.getInstance();
						modif.setTimeInMillis(ain.getObject().getDate_modif());
						aout.setDate(modif.getTime());
						//TODO: rights
						//binding description
						GenericActivityProperty ain_desc = ain
								.getGen_descriptions();
						String[] ain_desc_langs = ain_desc
								.getAvailableLanguages();
						for (int i = 0; (ain_desc_langs != null)
								&& (i < ain_desc_langs.length); i++) {
							String lang = ain_desc_langs[i];
							HyperTextType htx = objFactory
									.createHyperTextType();
							htx.setLang(lang);
							htx.getContent().add(ain_desc.getName(lang));
							aout.getAbstract().add(htx);
						}
						//binding relatedlinks
						AidaResource[] ain_res = ain.getResources();
						for (int i = 0; (ain_res != null)
								&& (i < ain_res.length); i++) {
							AidaResource res = ain_res[i];
							String[] langs = res.getAvailableLanguages();
							for (int j = 0; (langs != null)
									&& (j < langs.length); j++) {
								String lang = langs[j];
								DocLinkType dlt = objFactory
										.createDocLinkType();
								dlt.setUrl(res.getLink());
								dlt.setShortDesc(res.getDesc(lang));
								dlt.setLabel(res.getTitle(lang));
								aout.getRelatedLink().add(dlt);
							}
						}
						//adding project link
						DocLinkType dlt = objFactory.createDocLinkType();
						dlt.setLabel("Local Project Link");
						dlt.setLang(Constants.DEFAULT_LANGUAGE);
						dlt
								.setUrl(ctx + "/activity/view.jsp?id="
										+ ain.getId());
						aout.getRelatedLink().add(dlt);
						//binds project relations
						ActivityRelation[] rels = ain.getAct_relationsArray();
						for (int i = 0; (rels != null) && (i < rels.length); i++) {
							ActivityRelation relation = rels[i];
							RelatedType relt = objFactory.createRelatedType();
							//relt.setOrigin(relation.get
							//relt.setRelation(relation.get)
						}
						//binding orgs involved
						OrganizationInv[] orgs = ain.getOrganizations();
						for (int i = 0; (orgs != null) && (i < orgs.length); i++) {
							OrganizationInv inv = orgs[i];
							//we do not want to display the IDType
							// organizations
							if (!inv.getRole().getId().equals(
									OrganizationRole.BENEFICIARS_ORG_ROLE)
									|| !inv.getRole().getId().equals(
													OrganizationRole.CONTRACTING_ORG_ROLE))
								continue;
							Iterator langs = inv.getOrg().getName().languages();
							while (langs.hasNext()) {
								String lang = (String) langs.next();
								OrgRole role = objFactory.createOrgRole();
								OrgRoleType ort = objFactory
										.createOrgRoleType();
								ort.setLang(lang);
								
								if (inv.getRole().getId().equals(
										OrganizationRole.CONTRACTING_ORG_ROLE)) {
									ort.setValue(Translator_DB
											.getManager(token).getMessage(lang,
													"admin",
													"admin.implementingRole"));
									ort
											.setOrgRoleCode(Short
													.parseShort(Utils
															.getProperty(
																	token,
																	SysProp.IMPLEMENTING_ROLE)));
								}
								if (inv.getRole().getId().equals(
										OrganizationRole.BENEFICIARS_ORG_ROLE)) {
									ort.setValue(Translator_DB
											.getManager(token).getMessage(lang,
													"admin",
													"admin.executingRole"));
									ort.setOrgRoleCode(Short.parseShort(Utils
											.getProperty(token,
													SysProp.EXECUTING_ROLE)));
								}
								OrgType ot = objFactory.createOrgType();
								try {
									ot.setRefKey(orgs[i].getOrg().getAIDAOrg());
									ot.setLang(lang);
									ot.setValue(orgs[i].getOrg().getName()
											.getString(lang));
								} catch (NumberFormatException e) {
									e.printStackTrace();
								}
								ot.setLang(lang);
								//org.setAttributeAddedBy("RoDG");
								ot.setValue(inv.getOrg().getName().getString(
										lang));
								role.getRole().add(ort);
								role.setOrg(ot);
								aout.getOrgInvolved().add(role);
							}
						}
						//binding persons involved
						PersonInv[] perss = ain.getPersons();
						for (int i = 0; (perss != null) && (i < perss.length); i++) {
							PersonInv inv = perss[i];
							PersonRole pr = objFactory.createPersonRole();
							PersonType pt = objFactory.createPersonType();
							PersonRoleType prt = objFactory
									.createPersonRoleType();
							pt.setEmailAddress(inv.getPerson().getEmail());
							pt.setValue(inv.getPerson().getName());
							pr.setPerson(pt);
							aout.getPersonInvolved().add(pr);
						}
						//binding keywords
						GenericActivityProperty gen_keys = ain
								.getGen_keywords();
						String[] gen_keys_langs = gen_keys
								.getAvailableLanguages();
						for (int i = 0; (gen_keys_langs != null)
								&& (i < gen_keys_langs.length); i++) {
							String key = gen_keys.getName(gen_keys_langs[i]);
							StringTokenizer st = new StringTokenizer(key, ",");
							while (st.hasMoreTokens()) {
								FreeTextType kw = objFactory
										.createFreeTextType();
								kw.setLang(gen_keys_langs[i]);
								kw.setValue(st.nextToken());
								aout.getKeyword().add(kw);
							}
						}
						//binding anotherview
						/*
						 * KeyType kt = objFactory.createKeyType();
						 * kt.setDbKey(Long.toString(ain.getId()));
						 * kt.setOrigin((short) ain.getObject().getOrigin());
						 * kt.setValue(Long.toString(ain.getId()));
						 * aout.getAnotherView().add(kt);
						 */
						//binding formoreinfo --contracting contacts
						/*
						 * PersonInv[] con_pers =
						 * ain.getPersonsByLRId(OrganizationRole.CONTRACTING_ORG_ROLE);
						 * 
						 * for (int i = 0; (con_pers != null) && (i <
						 * con_pers.length); i++) { PersonInv inv = con_pers[i];
						 * HyperTextType htx = objFactory.createHyperTextType();
						 * htx.setLang(Constants.DEFAULT_LANGUAGE);
						 * 
						 * Person p = inv.getPerson(); List cont =
						 * htx.getContent(); cont.add("Name:" + p.getName());
						 * cont.add(" <br> Address:" + p.getAddress());
						 * cont.add(" <br> Country Name:" + p.getCountryName());
						 * cont.add(" <br> Postal Code:" + p.getPostalCode());
						 * cont.add(" <br> Field Of Activity:" +
						 * p.getDepartment()); cont.add(" <br> Phone:" +
						 * p.getPhone()); cont.add(" <br> Fax:" + p.getFax());
						 * cont.add(" <br> E-mail:" + p.getEmail());
						 * aout.getForMoreInfo().add(htx); }
						 * 
						 * //creates the Activities type,holding activity im
						 */
						HyperTextType htx = objFactory.createHyperTextType();
						htx.setLang(Constants.DEFAULT_LANGUAGE);
						List cont = htx.getContent();
						if (ain.getContact().getcName() != null)
							cont.add("Name:" + ain.getContact().getcName()
									+ "<br>");
						if (ain.getContact().getcTitle() != null)
							cont.add("Title:" + ain.getContact().getcTitle()
									+ "<br>");
						if (ain.getContact().getcEmail() != null)
							cont.add("Email:<b><i>"
									+ ain.getContact().getcEmail()
									+ "</i></b><br>");
						if (ain.getContact().getCountry_iso3() != null)
							cont.add("Country Code:"
									+ ain.getContact().getCountry_iso3()
									+ "<br>");
						if (ain.getContact().getAddr1() != null
								|| ain.getContact().getAddr2() != null)
							cont.add("Address:");
						if (ain.getContact().getAddr1() != null)
							cont.add(ain.getContact().getAddr1());
						if (ain.getContact().getAddr2() != null)
							cont.add("&nbsp;" + ain.getContact().getAddr2());
						if (ain.getContact().getPostalZip() != null)
							cont.add("<br>Zip Code:"
									+ ain.getContact().getPostalZip());
						if (ain.getContact().getcPhone() != null)
							cont.add("<br>Phone:"
									+ ain.getContact().getcPhone());
						if (ain.getContact().getcURL() != null)
							cont.add("<br>URL:" + ain.getContact().getcURL());
						aout.getForMoreInfo().add(htx);
						acts.getActivity().add(aout);
					}
					rs.close();
					ps.close();
					con.close();
					//project loop
				}
				//count if
			} catch (SQLException e) {
				e.printStackTrace();
			}
			//creating XML output
			PrintWriter out = response.getWriter();
			if ("true".equals(count)) {
				//output just the count XML...
				out.write(countOUT.toString());
				out.close();
			} else {
				//if needed, generate aidaSpider:
				if ((maxBlockSize != 0) && (nextFirstPrjID != 0)) {
					SpiderType spider = objFactory.createSpiderType();
					spider.setMaxBlockSize(BigInteger.valueOf(maxBlockSize));
					spider.setNextBlock(ctx + "/publisher.xml");
					spider.setStartWith(Long.toString(nextFirstPrjID));
					spider.setValue("");
					acts.setAidaSpider(spider);
				}
				Marshaller m = jc.createMarshaller();
				m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
		
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
			
				m.setProperty(Marshaller.JAXB_ENCODING, "ISO-8859-1");
				m.marshal(acts, bos);
				//replace the bad chrs!
				
				//byte[] ba = bos.toByteArray();
				/*for (int i = 0; i < ba.length; i++) {
					switch (ba[i]) {
						case (byte) 238 :
							ba[i] = 'i';
							break;
						case (byte) 226 :
							ba[i] = 'a';
							break;
						case (byte) 206 :
							ba[i] = 'I';
							break;
					}
				}*/
				out.write(bos.toString());
				StringBuffer sb=new StringBuffer();
				System.out.println(System.getProperty("file.encoding"));
				String defaultEncoding = new InputStreamReader(
			              new ByteArrayInputStream(new byte[0])).getEncoding();
				System.out.println(defaultEncoding);
				
				out.close();
			}
		} catch (JAXBException je) {
			je.printStackTrace();
		}
	}
}